﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JewererBasic.Models;
using JewererBasic.BO;
using JewererBasic.Classes;

namespace JewererBasic.Controllers
{
    public class ComponentController : Controller
    {
        private MSQDBEntities db = new MSQDBEntities();

        private List<TYPE> listTypes;
        private List<UNIT> listUnits;

        #region Index Home
        public ActionResult Index()
        {
            ImportedComponents.Clear();
            BagComponents.Clear();
            TestingComponents.Clear();

            listTypes = new List<TYPE>(db.TYPEs.ToList());
            listUnits = new List<UNIT>(db.UNITs.ToList());

            ViewBag.Types = listTypes;
            ViewBag.Units = listUnits;

            return View(db.COMPONENTs.ToList());
        }

        [HttpPost]
        public ActionResult Index(FormCollection fc)
        {
            ImportedComponents.Clear();
            BagComponents.Clear();
            TestingComponents.Clear();

            listTypes = new List<TYPE>(db.TYPEs.ToList());
            listUnits = new List<UNIT>(db.UNITs.ToList());

            ViewBag.Types = listTypes;
            ViewBag.Units = listUnits;

            string id = fc["txtId"];
            string name = fc["txtName"];
            string description = fc["txtDescription"];
            string typeId = fc["ddlType"];
            string unitId = fc["ddlUnit"];
            string weight = fc["txtWeight"];
            string quantity = fc["txtQuantity"];

            if (fc["submit"] == "ADD")
            {
                if (String.IsNullOrEmpty(id) || String.IsNullOrEmpty(name)
                    || String.IsNullOrEmpty(typeId) || String.IsNullOrEmpty(unitId))
                {
                    return View(db.COMPONENTs.ToList());
                }
                else
                {
                    try
                    {
                        COMPONENT Component = new COMPONENT();
                        Component.Id = id;
                        Component.Name = name;
                        Component.Decription = description;
                        Component.IdType = Int32.Parse(typeId);
                        Component.IdUnit = Int32.Parse(unitId);
                        Component.Weight = Double.Parse(weight);
                        Component.DayCreate = DateTime.Now;
                        Component.IdCreater = CurrentUser.UserID;

                        ComponentBO.Add(Component);
                    }
                    catch (Exception e)
                    {
                        return View(db.COMPONENTs.ToList());
                    }
                }
            }
            else if (fc["submit"] == "SEARCH")
            {
                string searchId = fc["txtSearchId"];
                string searchName = fc["txtSearchName"];
                return View(ComponentBO.Search(searchId, searchName));
            }
            else if (fc["submit"] == "IMPORT")
            {
                return RedirectToAction("Import");
            }
            else if (fc["submit"] == "STAFF EXP")
            {
                return RedirectToAction("TestingExport");
            }
            else if (fc["submit"] == "BAG EXP")
            {
                return RedirectToAction("BagExport");
            }
            else if (fc["submit"] == "HISTORY")
            {
                ClearSearchHistory();
                return RedirectToAction("History");
            }

            return View(db.COMPONENTs.ToList());
        }

        public ActionResult AddComponent(string id, string name, string description, int typeId, int unitId, float weight)
        {
            bool result = true;

            COMPONENT s = new COMPONENT();
            s.Id = id;
            s.Name = name;
            s.Decription = description;
            s.IdType = typeId;
            s.IdUnit = unitId;
            s.Weight = weight;
            s.DayCreate = DateTime.Now;
            s.IdCreater = CurrentUser.UserID;

            result = ComponentBO.Add(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Import
        private static List<ServiceComponent> ImportedComponents = new List<ServiceComponent>();
        public ActionResult Import()
        {
            ViewBag.CurrentUser = CurrentUser.UserID;
            ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();

            return View(ImportedComponents);
        }

        //[HttpPost]
        //public ActionResult Import(FormCollection fc)
        //{
        //    ViewBag.CurrentUser = CurrentUser.UserID;
        //    ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();

        //    string id = fc["txtId"];
        //    string weight = fc["txtWeight"];
        //    string quantity = fc["txtQuantity"];

        //    COMPONENT_IMPORT si = new COMPONENT_IMPORT();
        //    List<COMPONENT_IMPORTDETAIL> listSid = new List<COMPONENT_IMPORTDETAIL>();
        //    foreach (var item in ImportedComponents)
        //    {
        //        COMPONENT_IMPORTDETAIL sid = new COMPONENT_IMPORTDETAIL();
        //        sid.IdComponent = item.Id;
        //        sid.Weight = item.Weight;
        //        listSid.Add(sid);
        //    }

        //    ComponentBO.Import(si, listSid);
        //    ImportedComponents.Clear();

        //    return RedirectToAction("Index");
        //}

        public JsonResult SaveImport()
        {
            COMPONENT_IMPORT si = new COMPONENT_IMPORT();
            List<COMPONENT_IMPORTDETAIL> listSid = new List<COMPONENT_IMPORTDETAIL>();
            foreach (var item in ImportedComponents)
            {
                COMPONENT_IMPORTDETAIL sid = new COMPONENT_IMPORTDETAIL();
                sid.IdComponent = item.Id;
                sid.Weight = item.Weight;
                sid.Reason = item.Reason;
                listSid.Add(sid);
            }

            ComponentBO.Import(si, listSid);
            ImportedComponents.Clear();

            return Json(new { result = true, id = si.IdImport }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Testing Export
        public ActionResult TestingExportList()
        {
            return View(this.db.COMPONENT_EXPORTSTAFF.ToList());
        }

        public ActionResult TestingExportUpdate(int id)
        {
            COMPONENT_EXPORTSTAFF se = this.db.COMPONENT_EXPORTSTAFF.Find(id);
            if (se == null)
            {
                return RedirectToAction("TestingExportList");
            }

            if (se.IsFinish == 1) // finish
            {
                return RedirectToAction("TestingExportDetail", new { id = se.IdExport });
            }

            List<COMPONENT_EXPORTSTAFFDETAIL> list = se.COMPONENT_EXPORTSTAFFDETAIL.ToList();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    item.ReturnWeight = 0;
                    item.RejectWeight = 0;
                    item.ReturnDust = 0;
                }
            }

            ViewBag.ExportId = se.IdExport;

            return View(list);
        }

        [HttpPost]
        public ActionResult TestingExportUpdate(IEnumerable<COMPONENT_EXPORTSTAFFDETAIL> model, FormCollection fc)
        {
            string exportId = fc["exportId"];
            int id;
            if (Int32.TryParse(exportId, out id) == false)
            {
                return RedirectToAction("TestingExportList");
            }

            COMPONENT_EXPORTSTAFF se = this.db.COMPONENT_EXPORTSTAFF.Find(id);
            if (se == null)
            {
                return RedirectToAction("TestingExportList");
            }
            else
            {
                if (fc["submit"] == "Save")
                {
                    se.IsFinish = -1;
                }
                else if (fc["submit"] == "Finish")
                {
                    se.IsFinish = 1;
                }

                var query = from d in db.COMPONENT_EXPORTSTAFFDETAIL
                            where d.IdExport == se.IdExport
                            select d;
                if (query.Count() > 0)
                {
                    foreach (var item in query)
                    {
                        COMPONENT_EXPORTSTAFFDETAIL sesd = model.Where(m => m.IdComponent == item.IdComponent).First();
                        if (sesd != null)
                        {
                            item.ReturnWeight += sesd.ReturnWeight;
                            item.ReturnWeight = Math.Round(item.ReturnWeight, 3);
                            item.RejectWeight += sesd.RejectWeight;
                            item.RejectWeight = Math.Round(item.RejectWeight, 3);
                            item.ReturnDust += sesd.ReturnDust;
                            item.ReturnDust = Math.Round(item.ReturnDust, 3);

                            // cong weight vao component
                            COMPONENT c = this.db.COMPONENTs.Find(item.IdComponent);
                            if (c != null)
                            {
                                c.Weight += sesd.ReturnWeight + sesd.RejectWeight;
                                if (c.Weight.HasValue)
                                {
                                    c.Weight = Math.Round(c.Weight.Value, 3);
                                }
                                c.Dust += sesd.ReturnDust;
                                if (c.Dust.HasValue)
                                {
                                    c.Dust = Math.Round(c.Dust.Value, 3);
                                }
                                if(se.IsFinish==1)
                                    Waste_Report_BO.Update_Worker_Waste(item.COMPONENT_EXPORTSTAFF.IdStaff, item);
                            }
                        }
                    }
                }

                db.SaveChanges();

                return View("TestingExportDetail", se);
            }
        }

        public ActionResult TestingExportDetail(int id)
        {
            COMPONENT_EXPORTSTAFF se = this.db.COMPONENT_EXPORTSTAFF.Find(id);
            if (se == null)
            {
                return RedirectToAction("TestingExportList");
            }

            return View(se);
        }


        private static List<ServiceComponent> TestingComponents = new List<ServiceComponent>();
        private static string StaffId;
        public ActionResult TestingExport()
        {
            ViewBag.CurrentUser = CurrentUser.UserID;
            ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();
            ViewBag.Workers = this.db.EMPLOYEEs.ToList();

            return View(TestingComponents);
        }

        //[HttpPost]
        //public ActionResult TestingExport(FormCollection fc)
        //{
        //    ViewBag.CurrentUser = CurrentUser.UserID;
        //    ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();

        //    string id = fc["txtId"];
        //    string weight = fc["txtWeight"];
        //    string quantity = fc["txtQuantity"];
        //    string staffId = fc["txtStaffId"];

        //    if (String.IsNullOrEmpty(staffId) == false)
        //    {
        //        List<COMPONENT_EXPORTSTAFFDETAIL> listSesd = new List<COMPONENT_EXPORTSTAFFDETAIL>();
        //        foreach (var item in TestingComponents)
        //        {
        //            COMPONENT_EXPORTSTAFFDETAIL sesd = new COMPONENT_EXPORTSTAFFDETAIL();
        //            sesd.IdComponent = item.Id;
        //            sesd.Weight = item.Weight;
        //            listSesd.Add(sesd);
        //        }

        //        ComponentBO.ExportToStaff(staffId, listSesd);

        //        StaffId = "";
        //        ViewBag.StaffId = StaffId;
        //        TestingComponents.Clear();

        //        return RedirectToAction("Index");
        //    }

        //    return View(TestingComponents);
        //}

        public JsonResult SaveTestingExport(int staffId)
        {
            if (staffId != 0)
            {
                COMPONENT_EXPORTSTAFF ce = new COMPONENT_EXPORTSTAFF();
                List<COMPONENT_EXPORTSTAFFDETAIL> listSesd = new List<COMPONENT_EXPORTSTAFFDETAIL>();
                foreach (var item in TestingComponents)
                {
                    COMPONENT_EXPORTSTAFFDETAIL sesd = new COMPONENT_EXPORTSTAFFDETAIL();
                    sesd.IdComponent = item.Id;
                    sesd.Weight = item.Weight;
                    sesd.Dust = item.Dust;
                    sesd.ReturnWeight = 0;
                    sesd.RejectWeight = 0;
                    sesd.ReturnDust = 0;
                    sesd.Reason = item.Reason;
                    listSesd.Add(sesd);
                }

                ComponentBO.ExportToStaff(staffId, ce, listSesd);

                StaffId = "";
                ViewBag.StaffId = StaffId;
                TestingComponents.Clear();

                return Json(new { result = true, id = ce.IdExport }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { result = false, id = -1 }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Bag Export
        private static List<ServiceComponent> BagComponents = new List<ServiceComponent>();
        public ActionResult BagExport()
        {
            BagComponents = new List<ServiceComponent>();
            ViewBag.CurrentUser = CurrentUser.UserID;
            ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();
            ViewBag.Workers = this.db.EMPLOYEEs.ToList();

            return View(BagComponents);
        }

        private static List<BAG_COMPONENT> ComponentsInBag = new List<BAG_COMPONENT>();
        private static string CurrentBagId;
        private static int ReceiverId;
        [HttpPost]
        public ActionResult BagExport(FormCollection fc)
        {
            ViewBag.CurrentUser = CurrentUser.UserID;
            ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();
            ViewBag.Workers = this.db.EMPLOYEEs.ToList();

            string id = fc["txtId"];
            string weight = fc["txtWeight"];
            string quantity = fc["txtQuantity"];
            string bagId = fc["txtSearchBagId"];
            int receiver;
            if (Int32.TryParse(fc["receiver"], out receiver) == false)
            {
                receiver = 0;
            }

            if (fc["submit"] == "SEARCH")
            {
                BAG b = db.BAGs.Find(bagId);
                if (b != null)
                {
                    CurrentBagId = bagId;
                    ComponentsInBag = ComponentBO.Bagcomponents(bagId);
                    ViewBag.COMPONENTsInBag = ComponentsInBag;
                    ViewBag.CurrentBagId = CurrentBagId;
                }
            }
            else if (fc["submit"] == "FINISH")
            {
                //if (String.IsNullOrEmpty(CurrentBagId) == false)
                //{
                //    List<BAG_COMPONENT> listSeb = new List<BAG_COMPONENT>();
                //    foreach (var item in BagComponents)
                //    {
                //        BAG_COMPONENT bs = new BAG_COMPONENT();
                //        bs.IdComponent = item.Id;
                //        bs.Weight = item.Weight;
                //        listSeb.Add(bs);
                //    }

                //    ComponentBO.ExportToBag(CurrentBagId, listSeb);

                //    BagComponents.Clear();
                //    ComponentsInBag.Clear();
                //    CurrentBagId = "";

                //    return RedirectToAction("Index");
                //}
            }

            ViewBag.COMPONENTsInBag = ComponentsInBag;
            ViewBag.CurrentBagId = CurrentBagId;
            ReceiverId = receiver;
            ViewBag.Receiver = ReceiverId;

            return View(BagComponents);
        }

        public JsonResult SaveBagExport(int receiver)
        {
            if (String.IsNullOrEmpty(CurrentBagId) == false && receiver != 0)
            {
                COMPONENT_EXPORTBAG ce = new COMPONENT_EXPORTBAG();
                List<BAG_COMPONENT> listSeb = new List<BAG_COMPONENT>();
                foreach (var item in BagComponents)
                {
                    BAG_COMPONENT bs = new BAG_COMPONENT();
                    bs.IdComponent = item.Id;
                    bs.Weight = item.Weight;
                    bs.Dust = item.Dust;
                    listSeb.Add(bs);
                }

                ComponentBO.ExportToBag(CurrentBagId, receiver, ce, listSeb, BagComponents);

                BagComponents.Clear();
                ComponentsInBag.Clear();
                CurrentBagId = "";

                return Json(new { result = true, id = ce.IdExport }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { result = false, id = -1 }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region History
        private static string id;
        private static DateTime? makedDateFrom;
        private static DateTime? makedDateTo;
        private static bool importBool = true;
        private static bool exportToStaffBool = true;
        private static bool exportToBagBool = true;
        public ActionResult History()
        {
            ViewBag.Id = id;
            ViewBag.MakedDateFrom = makedDateFrom == null ? null : makedDateFrom.Value.ToString("yyyy-MM-dd");
            ViewBag.MakedDateTo = makedDateTo == null ? null : makedDateTo.Value.ToString("yyyy-MM-dd");
            ViewBag.ImportBool = importBool;
            ViewBag.ExportToStaffBool = exportToStaffBool;
            ViewBag.ExportToBagBool = exportToBagBool;

            return View(ComponentBO.History(id, makedDateFrom, makedDateTo, Convert.ToBoolean(importBool), Convert.ToBoolean(exportToBagBool), Convert.ToBoolean(exportToStaffBool)));
        }

        [HttpPost]
        public ActionResult History(FormCollection fc)
        {
            if (fc["submit"] == "HISTORY")
            {
                id = fc["txtIdComponent"];
                string dateFrom = fc["makedDateFrom"];
                string dateTo = fc["makedDateTo"];
                string import = fc["ckboxImport"];
                string exportToStaff = fc["ckboxExportToStaff"];
                string exportToBag = fc["ckboxExportToBag"];

                makedDateFrom = null;
                if (String.IsNullOrEmpty(dateFrom) == false)
                {
                    makedDateFrom = Convert.ToDateTime(dateFrom);
                }
                makedDateTo = null;
                if (String.IsNullOrEmpty(dateTo) == false)
                {
                    makedDateTo = Convert.ToDateTime(dateTo);
                }

                bool tmp;
                importBool = false;
                exportToStaffBool = false;
                exportToBagBool = false;

                if (Boolean.TryParse(import, out tmp) == false)
                {
                    importBool = true;
                }
                if (Boolean.TryParse(exportToStaff, out tmp) == false)
                {
                    exportToStaffBool = true;
                }
                if (Boolean.TryParse(exportToBag, out tmp) == false)
                {
                    exportToBagBool = true;
                }
            }
            else if (fc["submit"] == "CLEAR")
            {
                ClearSearchHistory();
            }

            ViewBag.Id = id;
            ViewBag.MakedDateFrom = makedDateFrom == null ? null : makedDateFrom.Value.ToString("yyyy-MM-dd");
            ViewBag.MakedDateTo = makedDateTo == null ? null : makedDateTo.Value.ToString("yyyy-MM-dd");
            ViewBag.ImportBool = importBool;
            ViewBag.ExportToStaffBool = exportToStaffBool;
            ViewBag.ExportToBagBool = exportToBagBool;

            return View(ComponentBO.History(id, makedDateFrom, makedDateTo, Convert.ToBoolean(importBool), Convert.ToBoolean(exportToBagBool), Convert.ToBoolean(exportToStaffBool)));
        }

        private void ClearSearchHistory()
        {
            id = "";
            makedDateFrom = null;
            makedDateTo = null;
            importBool = true;
            exportToBagBool = true;
            exportToStaffBool = true;
        }
        #endregion

        #region Json
        public ActionResult SaveToDb(List<ComponentViewModel> Components)
        {
            bool result = true;

            foreach (var item in Components)
            {
                COMPONENT Component = new COMPONENT();
                Component.Id = item.Id;
                Component.Name = item.Name;
                Component.Decription = item.Description;
                int x = db.TYPEs.Where(m => m.Name == item.Type).Select(m => m.Id).FirstOrDefault();
                if (x == 0)
                {
                    Component.IdType = null;
                }
                else
                {
                    Component.IdType = x;
                }
                Component.IdUnit = db.UNITs.Where(m => m.Name == item.Unit).Select(m => m.Id).FirstOrDefault();
                Component.Weight = item.Weight;
                Component.Dust = 0;
                Component.DayCreate = DateTime.Now;
                Component.IdCreater = CurrentUser.UserID;

                ComponentBO.Add(Component);
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetTypes(string query = null)
        {
            var result = from d in db.TYPEs
                         where d.Name.Contains(query)
                         select new { d.Id, d.Name };
            var s = result.ToList();
            return Json(result.ToList(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetUnits(string query = null)
        {
            var result = from d in db.UNITs
                         where d.Name.Contains(query)
                         select new { d.Id, d.Name };
            var s = result.ToList();
            return Json(result.ToList(), JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsTypeNameExisted(string typeName)
        {
            bool result;

            var query = (from d in db.TYPEs
                         where d.Name == typeName
                         select d).FirstOrDefault();

            if (query == null)
            {
                result = false;
            }
            else
            {
                result = true;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsUnitNameExisted(string unitName)
        {
            bool result;

            var query = (from d in db.UNITs
                         where d.Name == unitName
                         select d).FirstOrDefault();

            if (query == null)
            {
                result = false;
            }
            else
            {
                result = true;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetComponentInBag(string bagId, string ComponentId)
        {
            bool result = true;

            if (bagId == null || ComponentId == null)
            {
                result = false;
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }

            var query = (from d in db.BAG_COMPONENT
                         where d.IdBag == bagId && d.IdComponent == ComponentId
                         select d).FirstOrDefault();

            if (query == null)
            {
                result = false;
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { result, weight = query.TotalWeight - query.Weight }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ClearImportForm()
        {
            bool result = true;

            ImportedComponents.Clear();

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ClearTestingExportForm()
        {
            bool result = true;

            TestingComponents.Clear();
            StaffId = "";

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ClearBagExportForm()
        {
            bool result = true;

            BagComponents.Clear();
            ComponentsInBag.Clear();
            CurrentBagId = "";

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsComponentExisted(string id)
        {
            bool result;

            COMPONENT p = db.COMPONENTs.Find(id);
            if (p == null)
            {
                result = false;
            }
            else
            {
                result = true;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsComponentExistedInBag(string bagId, string ComponentId)
        {
            bool result = true;

            if (bagId == null || ComponentId == null)
            {
                result = false;
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }

            var query = (from d in db.BAG_COMPONENT
                         where d.IdBag == bagId && d.IdComponent == ComponentId
                         select d).FirstOrDefault();

            if (query == null)
            {
                result = false;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AddImport(string id, float weight, string reason)
        {
            bool result = true;

            ImportedComponents.Add(new ServiceComponent() { Id = id, Weight = weight, Reason = reason  });

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AddTestingExport(string id, float weight, float dust, string reason)
        {
            bool result = true;

            TestingComponents.Add(new ServiceComponent() { Id = id, Weight = weight, Dust = dust, Reason = reason  });

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AddBagExport(string bagId, string ComponentId, float weightIn, float dust, string reason)
        {
            bool result = true;

            if (bagId == null || ComponentId == null)
            {
                result = false;
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }

            var query = (from d in db.BAG_COMPONENT
                         where d.IdBag == bagId && d.IdComponent == ComponentId
                         select d).FirstOrDefault();

            if (query == null)
            {
                result = false;
                return Json(new { result }, JsonRequestBehavior.AllowGet);
            }

            //if ((double)weightIn > query.TotalWeight - query.Weight)
            //{
            //    result = false;
            //}
            //else
            //{
                
            //}

            BagComponents.Add(new ServiceComponent() { Id = ComponentId, Weight = weightIn, Dust = dust, Reason = reason });

            return Json(new { result, weight = query.TotalWeight - query.Weight }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetComponents(string query = null)
        {
            var result = from d in db.COMPONENTs
                         where d.Id.Contains(query)
                         select d.Id;
            var s = result.ToList();
            return Json(result.ToList(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetComponentNames(string query = null)
        {
            var result = from d in db.COMPONENTs
                         where d.Name.Contains(query)
                         select d.Name;

            return Json(result.Distinct().ToList(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetBagIds(string query = null)
        {
            var result = from d in db.BAGs
                         where d.Id.Contains(query)
                         select d.Id;
            var s = result.ToList();
            return Json(result.ToList(), JsonRequestBehavior.AllowGet);
        }

        public JsonResult Update(string id, string name, string description)
        {
            bool result = true;

            COMPONENT s = new COMPONENT() { Id = id, Name = name, Decription = description };
            ComponentBO.Update(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Delete(string id)
        {
            bool result = true;

            ComponentBO.Delete(id);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult UpdateImportComponent(string id, double weight, string reason)
        {
            bool result = true;

            ServiceComponent s = ImportedComponents.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
            {
                s.Weight = weight;
                s.Reason = reason;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteImportComponent(string id)
        {
            bool result = true;

            ServiceComponent s = ImportedComponents.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
                ImportedComponents.Remove(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult UpdateTestingExportComponent(string id, double weight, double dust, string reason)
        {
            bool result = true;

            ServiceComponent s = TestingComponents.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
            {
                s.Weight = weight;
                s.Dust = dust;
                s.Reason = reason;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteTestingExportComponent(string id)
        {
            bool result = true;

            ServiceComponent s = TestingComponents.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
                TestingComponents.Remove(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult UpdateBagExportComponent(string id, double weight, double dust, string reason)
        {
            bool result = true;

            ServiceComponent s = BagComponents.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
            {
                s.Weight = weight;
                s.Dust = dust;
                s.Reason = reason;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteBagExportComponent(string id)
        {
            bool result = true;

            ServiceComponent s = BagComponents.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
                BagComponents.Remove(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        //Sang add
        // Create complex component
        //public ActionResult CreateComponent()
        //{
        //    COMPONENT component = new COMPONENT();
        //    component.IdUnit = 1;

        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());
        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());
        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());
        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());
        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());
        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());
        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());
        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());
        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());
        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());
        //    component.COMPONENT_MOLECULE.Add(new COMPONENT_MOLECULE());

        //    this.SetViewBag();

        //    return View(component);
        //}

        //void SetViewBag()
        //{
        //    MSQDBEntities db = new MSQDBEntities();
        //    ViewBag.IdUnit = new SelectList(db.UNITs.ToList(), "Id", "Name");
        //    ViewBag.IdType = new SelectList(db.TYPEs.ToList(), "Id", "Name");
        //    ViewBag.Error = "";
        //}

        //[HttpPost]
        //public ActionResult CreateComponent(COMPONENT models)
        //{
        //    string error = "";
        //    if (ModelState.IsValid)
        //    {
        //        error = ComponentBO.CheckComponentId(models.COMPONENT_MOLECULE.Select(m=>m.SlaveComponentId).ToList());
        //        if (string.IsNullOrEmpty(error))
        //        {
        //            ComponentBO.AddComplexComponent(models);
        //            return RedirectToAction("Index", "Component");
        //        }                
        //    }            
        //    this.SetViewBag();
        //    ViewBag.Error = error;
        //    return View(models);
        //}
        //public JsonResult ComponentAutoComplete(string query = "")
        //{
        //    MSQDBEntities db = new MSQDBEntities();
        //    if (string.IsNullOrEmpty(query))
        //    {
        //        return Json(db.COMPONENTs.ToList(), JsonRequestBehavior.AllowGet);
        //    }
        //    var result = from d in db.COMPONENTs
        //                 where d.Id.Contains(query)
        //                 select d.Id;
        //    return Json(result.ToList(), JsonRequestBehavior.AllowGet);
        //}
        // End add
    }
}